package org.ze.chatbot.api.domain.blbl.service;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.ze.chatbot.api.domain.blbl.IBlblApi;
import org.ze.chatbot.api.domain.blbl.model.aggregates.UnAnsweredQuestionsAggregates;
import org.ze.chatbot.api.domain.blbl.model.res.AnswerRes;
import org.ze.chatbot.api.domain.blbl.model.res.RespData;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class BlblApi implements IBlblApi {

    private Logger logger = LoggerFactory.getLogger(BlblApi.class);

    @Override
    public UnAnsweredQuestionsAggregates queryUnAnsweredQuestionsRpid(String oid , String cookie) throws IOException {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        HttpGet get = new HttpGet("https://api.bilibili.com/x/v2/reply/main?csrf=799fe818d8b76fa8eabe4fc941af8c1b&mode=2&oid="+oid+"&pagination_str=%7B%22offset%22:%22%22%7D&plat=1&seek_rpid=0&type=17");

        get.addHeader("cookie", cookie);
        get.addHeader("Content-Type", "application/json;charset=utf8");

        CloseableHttpResponse response = httpClient.execute(get);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String jsonStr = EntityUtils.toString(response.getEntity());
            jsonStr = JSON.parseObject(jsonStr).get("data").toString();
            logger.info("拉取提问数据:jsonStr：{}",jsonStr);
            return JSON.parseObject(jsonStr, UnAnsweredQuestionsAggregates.class);
        } else {
            throw new RuntimeException("queryUnAnsweredQuestionsTopicId Err Code is " + response.getStatusLine().getStatusCode());
        }
    }

    @Override
    public String answer(String cookie, String message, String oid,String parent) throws IOException {

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        HttpPost post = new HttpPost("https://api.bilibili.com/x/v2/reply/add");
        post.addHeader("cookie", cookie);
        post.addHeader("Content-Type", "application/x-www-form-urlencoded");
        post.addHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 Edg/116.0.1938.54");
        //构造测试数据
        List<NameValuePair> param = new ArrayList<NameValuePair>();
        param.add(new BasicNameValuePair("csrf","3bb4cf219c265d63fb5312a7a191db1c"));
        param.add(new BasicNameValuePair("message",message));
        param.add(new BasicNameValuePair("oid",oid));
        param.add(new BasicNameValuePair("parent",parent));
        param.add(new BasicNameValuePair("root",parent));
        param.add(new BasicNameValuePair("type","17"));

        //生成装载param的entity
        HttpEntity entity = new UrlEncodedFormEntity(param, "utf-8");
        post.setEntity(entity);

        CloseableHttpResponse response = httpClient.execute(post);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String jsonStr = EntityUtils.toString(response.getEntity());
            logger.info("回答问题结果: message：{},oid：{},parent：{},jsonStr：{}", message,oid,parent,jsonStr);
            jsonStr = JSON.parseObject(jsonStr).get("data").toString();
            AnswerRes answerRes = JSON.parseObject(jsonStr, AnswerRes.class);
            return answerRes.isSucceeded();
        } else {
            throw new RuntimeException("answer Err Code is " + response.getStatusLine().getStatusCode());
        }
    }

}